package com.leetcode.math;

/**
 * @author Dennis Li
 * @date 2020/9/22 11:17
 */
public class MyPow_50 {

    //Integer.MAX_VALUE是2147483647，而Integer.MIN_VALUE是-2147483648，两个不是相反数关系，
    // 并且对MAX_VALUE取反得到的是MIN_VALUE而不是-2147483647
    public double myPow(double x, int n) {
        double ans = 1.0, start = x;
        long exp = Math.abs((long) n);
        while (exp > 0) {
            if ((exp & 1) == 1) {
                ans *= start;
            }
            start *= start;
            exp >>= 1;
        }
        return n >= 0 ? ans : 1.0 / ans;
    }

    static class Solution {
        public double myPow(double x, int n) {
            long exp = Math.abs((long) n);
            double res = 1.0, base = x;
            while (exp > 1) {
                if ((exp & 1) == 1) {
                    res *= base;
                }
                base *= base;
                exp >>= 1;
            }
            return n >= 0 ? res : 1.0 / res;
        }
    }

}
